package com.repro.lib_base.bases.vm

import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.fragment.app.createViewModelLazy
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner

//VM扩展类

/**
 * Activity创建ViewModel
 */
@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.createViewModel(noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null): VM {
    val factoryProducer: () -> ViewModelProvider.Factory = factoryProducer ?: {
        defaultViewModelProviderFactory
    }
    return ViewModelLazy(VM::class, { viewModelStore }, factoryProducer).value
}

/**
 * Fragment创建ViewModel
 */
@MainThread
inline fun <reified VM : ViewModel> Fragment.createViewModel(
    noinline owner: () -> ViewModelStoreOwner = { this },
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): VM = createViewModelLazy(VM::class, { owner().viewModelStore }, factoryProducer).value

/**
 * Fragment创建Activity中的ViewModel
 */
@MainThread
inline fun <reified VM : ViewModel> Fragment.createActivityVM(
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): VM = createViewModelLazy(VM::class, { requireActivity().viewModelStore }, factoryProducer ?: {
    defaultViewModelProviderFactory
}).value